package com.tengju.bff.infrastructure.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.tengju.bff.infrastructure.shared.MqMessageConstants.ABM_ROLE_LEVEL_EXCHANGE;
import static com.tengju.bff.infrastructure.shared.MqMessageConstants.TJ_ROLE_LEVEL_QUEUE;

@Configuration
@Slf4j
public class AbmGradeRabbitMqConfig {

    @Value("${abmGrade.rabbitmq.host}")
    private String host;
    @Value("${abmGrade.rabbitmq.port}")
    private Integer port;
    @Value("${abmGrade.rabbitmq.username}")
    private String username;
    @Value("${abmGrade.rabbitmq.password}")
    private String password;
    @Value("${abmGrade.rabbitmq.virtual-host}")
    private String vhost;


    @Bean(name = "abmGradeAmqpAdmin")
    public AmqpAdmin abmGradeAmqpAdmin(@Qualifier("abmGradeConnectionFactory") ConnectionFactory connectionFactory) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        Queue queue = new Queue(TJ_ROLE_LEVEL_QUEUE, true);
        rabbitAdmin.declareQueue(queue);
        rabbitAdmin.declareBinding(BindingBuilder.bind(queue).to(new FanoutExchange(ABM_ROLE_LEVEL_EXCHANGE)));
        return rabbitAdmin;
    }

    @Bean(name = "abmGradeConnectionFactory")
    public ConnectionFactory abmGradeConnectionFactory() {
        CachingConnectionFactory factory = new CachingConnectionFactory();
        factory.setHost(host);
        factory.setPort(port);
        factory.setUsername(username);
        factory.setPassword(password);
        factory.setVirtualHost(vhost);
        return factory;
    }

    @Bean(name = "abmGradeContainerFactory")
    public SimpleRabbitListenerContainerFactory abmGradeListenerFactory(SimpleRabbitListenerContainerFactoryConfigurer configurer,
                                                                        @Qualifier("abmGradeConnectionFactory") ConnectionFactory abmGradeConnectionFactory) {
        SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory = new SimpleRabbitListenerContainerFactory();
        simpleRabbitListenerContainerFactory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        configurer.configure(simpleRabbitListenerContainerFactory, abmGradeConnectionFactory);
        return simpleRabbitListenerContainerFactory;
    }


}
